package com.th.apicenter.xinlang;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.th.apicenter.mapper.ThXlDataMapper;
import com.th.apicenter.tools.ThResult;
import com.th.apicenter.tools.ThTools;
import com.th.apicenter.xinlang.dto.ThXlExcelDTO;
import com.th.apicenter.xinlang.entity.ThXlData;
import com.th.apicenter.xinlang.service.XinlangService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/xl")
@Slf4j
public class XinlangController {

    @Autowired
    private XinlangService xinlangService;

    @Resource
    private ThXlDataMapper thXlDataMapper;

    /**
     * 接收新浪的数据
     * http://xlapi.tinghongzz.com/xl/receive?group_id={GroupId}&model={Model}&os_type={OsType}
     * &os_ver={OsVer}&imei={Imei}&caid={Caid}&idfa={Idfa}&oaid={Oaid}&oaid_md5={OaidMd5}
     * &caid_json={CaidJson}&ts={Ts}
     *
     * @return
     */
    @GetMapping("/receive")
    public ThResult receiveUrl(@RequestParam(name = "group_id", required = false) String group_id,
                                @RequestParam(name = "model", required = false) String model,
                                @RequestParam(name = "os_type", required = false) String os_type,
                                @RequestParam(name = "os_ver", required = false) String os_ver,
                                @RequestParam(name = "imei", required = false) String imei,
                                @RequestParam(name = "caid", required = false) String caid,
                                @RequestParam(name = "idfa", required = false) String idfa,
                                @RequestParam(name = "oaid", required = false) String oaid,
                                @RequestParam(name = "oaid_md5", required = false) String oaid_md5,
                                @RequestParam(name = "caid_json", required = false) String caid_json,
                                @RequestParam(name = "ts", required = false) String ts,
                                @RequestParam(name = "click_id", required = false) String click_id,
                                @RequestParam(name = "lintem_id", required = false) String lintem_id,
                                @RequestParam(name = "ad_id", required = false) String ad_id,
                                @RequestParam(name = "cnv_id", required = false) String cnv_id) {
        log.info("接收到新浪上报的数据");
        log.info("group_id:{}", group_id);
        log.info("model:{}", model);
        log.info("os_type:{}", os_type);
        log.info("os_ver:{}", os_ver);
        log.info("click_id:{}", click_id);
        log.info("lintem_id:{}", lintem_id);
        log.info("ad_id:{}", ad_id);
        log.info("cnv_id:{}", cnv_id);
        log.info("imei:{}", imei);
        log.info("caid:{}", caid);
        log.info("idfa:{}", idfa);
        log.info("oaid:{}", oaid);
        log.info("oaid_md5:{}", oaid_md5);
        log.info("caid_json:{}", caid_json);
        log.info("ts:{}", ts);
        ThXlData thXlData = new ThXlData();
        thXlData.setGroupId(ThTools.isNull(group_id) ? "" : group_id);
        thXlData.setModel(ThTools.isNull(model) ? "" : model);
        thXlData.setOsType(ThTools.isNull(os_type) ? "" : os_type);
        thXlData.setOsVer(ThTools.isNull(os_ver) ? "" : os_ver);
        thXlData.setClickId(ThTools.isNull(click_id) ? "" : click_id);
        thXlData.setLintemId(ThTools.isNull(lintem_id) ? "" : lintem_id);
        thXlData.setAdId(ThTools.isNull(ad_id) ? "" : ad_id);
        thXlData.setCnvId(ThTools.isNull(cnv_id) ? "" : cnv_id);
        thXlData.setImei(ThTools.isNull(imei) ? "" : imei);
        thXlData.setCaid(ThTools.isNull(caid) ? "" : caid);
        thXlData.setIdfa(ThTools.isNull(idfa) ? "" : idfa);
        thXlData.setOaid(ThTools.isNull(oaid) ? "" : oaid);
        thXlData.setOaidMd5(ThTools.isNull(oaid_md5) ? "" : oaid_md5);
        thXlData.setCaidJson(ThTools.isNull(caid_json) ? "" : caid_json);
        thXlData.setTs(ThTools.isNull(ts) ? "" : ts);
        thXlData.setCreateTime(new Date());

        String receive = xinlangService.receive(thXlData);
        return ThResult.success(receive);
    }


    /**
     * 接收新浪的数据
     * http://apibiz.tinghongzz.com/xl/active?group_id={GroupId}&model={Model}&os_type={OsType}
     * &os_ver={OsVer}&imei={Imei}&caid={Caid}&idfa={Idfa}&oaid={Oaid}&oaid_md5={OaidMd5}
     * &caid_json={CaidJson}&ts={Ts}
     *
     * @return
     */
    @GetMapping("/active")
    public ThResult activeUrl(@RequestParam(name = "group_id", required = false) String group_id,
                               @RequestParam(name = "model", required = false) String model,
                               @RequestParam(name = "os_type", required = false) String os_type,
                               @RequestParam(name = "os_ver", required = false) String os_ver,
                               @RequestParam(name = "imei", required = false) String imei,
                               @RequestParam(name = "caid", required = false) String caid,
                               @RequestParam(name = "idfa", required = false) String idfa,
                               @RequestParam(name = "oaid", required = false) String oaid,
                               @RequestParam(name = "oaid_md5", required = false) String oaid_md5,
                               @RequestParam(name = "caid_json", required = false) String caid_json,
                               @RequestParam(name = "ts", required = false) String ts,
                               @RequestParam(name = "click_id", required = false) String click_id,
                               @RequestParam(name = "lintem_id", required = false) String lintem_id,
                               @RequestParam(name = "ad_id", required = false) String ad_id,
                               @RequestParam(name = "cnv_id", required = false) String cnv_id) {
        log.info("接收到新浪上报的数据");
        log.info("group_id:{}", group_id);
        log.info("model:{}", model);
        log.info("os_type:{}", os_type);
        log.info("os_ver:{}", os_ver);
        log.info("click_id:{}", click_id);
        log.info("lintem_id:{}", lintem_id);
        log.info("ad_id:{}", ad_id);
        log.info("cnv_id:{}", cnv_id);
        log.info("imei:{}", imei);
        log.info("caid:{}", caid);
        log.info("idfa:{}", idfa);
        log.info("oaid:{}", oaid);
        log.info("oaid_md5:{}", oaid_md5);
        log.info("caid_json:{}", caid_json);
        log.info("ts:{}", ts);
        ThXlData thXlData = new ThXlData();
        thXlData.setGroupId(ThTools.isNull(group_id) ? "" : group_id);
        thXlData.setModel(ThTools.isNull(model) ? "" : model);
        thXlData.setOsType(ThTools.isNull(os_type) ? "" : os_type);
        thXlData.setOsVer(ThTools.isNull(os_ver) ? "" : os_ver);
        thXlData.setClickId(ThTools.isNull(click_id) ? "" : click_id);
        thXlData.setLintemId(ThTools.isNull(lintem_id) ? "" : lintem_id);
        thXlData.setAdId(ThTools.isNull(ad_id) ? "" : ad_id);
        thXlData.setCnvId(ThTools.isNull(cnv_id) ? "" : cnv_id);
        thXlData.setImei(ThTools.isNull(imei) ? "" : imei);
        thXlData.setCaid(ThTools.isNull(caid) ? "" : caid);
        thXlData.setIdfa(ThTools.isNull(idfa) ? "" : idfa);
        thXlData.setOaid(ThTools.isNull(oaid) ? "" : oaid);
        thXlData.setOaidMd5(ThTools.isNull(oaid_md5) ? "" : oaid_md5);
        thXlData.setCaidJson(ThTools.isNull(caid_json) ? "" : caid_json);
        thXlData.setTs(ThTools.isNull(ts) ? "" : ts);
        thXlData.setCreateTime(new Date());

        String receive = xinlangService.active(thXlData);
        return ThResult.success(receive);
    }


    @GetMapping("/exportData")
    public void exportData(HttpServletResponse response,
                           @RequestParam(name = "adid", required = false) String adid,
                           @RequestParam(name = "time", required = false) String time) {
        String startTime = time + " 00:00:00";
        String endTime = time + " 23:59:59";
        List<ThXlExcelDTO> thXlExcelDTOS = thXlDataMapper.queryDataByExcel(adid, startTime, endTime);
        ExcelWriter writer = ExcelUtil.getWriter(true); // true 表示使用 xlsx 格式
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            String fileName = URLEncoder.encode("新浪" + time + "数据.xlsx", "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            // 写入数据（自动识别 @Alias 注解生成表头）
            writer.write(thXlExcelDTOS, true);
            // 将 Excel 流写入响应
            writer.flush(response.getOutputStream(), true);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            response.reset(); // 清空已写入的数据
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            e.printStackTrace();
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

}
